// pages/mes/more-product/more-product.js
const sizeType = [
    ['compressed'],
    ['original']
];
const uploadFile = require('../../../lib/aliyun/uploadAliyun.js');
const app = getApp();
import Toast from '../../../component/toast/toast';
let imgCoverIndex = -1,videoCoverIndex = -1
Page({

    /**
     * 页面的初始数据
     */
    data: {
        position: 1,
        pageSize:6,
        pageIndex:-1,
        hasMore:true,
        imgArr:[],
        videoArr:[],
        currentTotal:0,
        flag:true,
        userInfoId:''
    },
    // 事件函数
    setCoverClick(e){
        let index = e.currentTarget.dataset.index;
        if(this.data.position == 1){
            //图片
            this.setWorksCover(this.data.imgArr[index].FileUrl , index);
        }else{
            //视频
            this.setWorksCover(this.data.videoArr[index].FileUrl, index);
        }
    },
    longSelectItem(e) {
        if(!this.data.flag){
            return;
        }
        let index = e.currentTarget.dataset.index;
        let that = this;
        wx.showModal({
            title: '移除作品',
            content: '确认要移除当前作品吗？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#e71015',
            confirmText: '确认',
            confirmColor: '#333333',
            success: function(res) {
                if (res.confirm) {
                    if (that.data.position == 1) {
                        //图片
                        that.deleteWork(that.data.imgArr[index].Id, index);
                    } else {
                        //视频
                        that.deleteWork(that.data.videoArr[index].Id, index);
                    }
                }
            }
        });
    },
    selectItem(e){
        let index = e.currentTarget.dataset.index;
        if(this.data.position == 2){
            // console.log(this.data.videoArr[index]);
            app.globalData.globalWebUrl = this.data.videoArr[index].FileUrl;
            wx.navigateTo({
                url: '/pages/agreement-web/agreement-web?title=视频播放'
            })
        }else{
            wx.previewImage({
                current: this.data.imgArr[index].FileUrl, 
                urls: [this.data.imgArr[index].FileUrl] 
            })
        }
    },
    clickItem:function(event) {
        let index = event.target.id;
        this.setData({
            position: index,
            hasMore:true,
            pageIndex:-1,
            imgArr:[],
            videoArr:[]
        });
        this.getMyWorks(false);
    },
    addRes(){
        let that = this;
        if(this.data.position == 1){
            wx.chooseImage({
                sizeType: sizeType[0],
                count: 1,
                success(res) {
                    that.localUploadFile(res.tempFilePaths[0]);
                }
            })
        }else{
            wx.chooseVideo({
                sourceType: ['album', 'camera'],
                maxDuration: 60,
                camera: 'back',
                success(res) {
                    that.localUploadFile(res.tempFilePath);
                }
            })
        }
    },
    // 网络请求
    deleteWork(id , index){
        let that = this;
        wx.showLoading({
            title: '提交中...',
            mask:true
        });
        wx.request({
            url: app.globalData.serverAddress.deleteWork,
            data: {
                Id: id,
                CurrentUserInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    if(that.data.position == 1){
                        that.data.imgArr.splice(index, 1);
                        that.setData({
                            imgArr: that.data.imgArr
                        });
                    }else{
                        that.data.videoArr.splice(index, 1);
                        that.setData({
                            videoArr: that.data.videoArr
                        });
                    }
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                console.log("deleteWork fail："+JSON.stringify(res));
            },
            complete: function(res) {wx.hideLoading();},
        })
    },
    setWorksCover(fileUrl , index){
        wx.showLoading({
            title: '提交中...',
            mask:true
        })
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.setWorksCover,
            data: {
                CurrentUserInfoId:app.userInfo.Id,
                FileUrl:fileUrl
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let arr = '';
                    let front = `videoArr[0].IsCover`;
                    if(that.data.position == 1){
                        arr = `imgArr[${index}].IsCover`;
                        if(imgCoverIndex != -1){
                            front = `imgArr[${imgCoverIndex}].IsCover`;
                            that.setData({
                                [front]: 0
                            });
                        }
                        imgCoverIndex = index;
                    }else{
                        arr = `videoArr[${index}].IsCover`;
                        if(videoCoverIndex != -1){
                            front = `videoArr[${videoCoverIndex}].IsCover`;
                            that.setData({
                                [front]: 0
                            });
                        }
                        videoCoverIndex = index;
                    }
                    that.setData({
                        [arr]: 1
                    });
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                console.log("setWorksCover fail:"+JSON.stringify(res));
            },
            complete: function(res) { wx.hideLoading();},
        })
    },
    localUploadFile(filePath){
        wx.showLoading({
            title: '上传中...',
            mask: true
        })
        this.uploadSyncFile(filePath).then(res => {
            if (res.statusCode == 200) {
                this.addUserWorks(res.imgUrl);
            }

        }, err => {
            wx.hideLoading();
            Toast("图片上传失败，请检查网络");
            console.log(err);
        });
    },
    addUserWorks(filePath){
        let that = this;
        let fileType = 0;
        if (this.data.position ==2){
            fileType = 1;
        }
        wx.request({
            url: app.globalData.serverAddress.addUserInfoWorks,
            data: {
                Id:'',
                UserInfoId: app.userInfo.Id,
                FileType: fileType,
                FileUrl: filePath,
                SortNo:0
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000){
                    // console.log(res.data);
                    that.setData({
                        pageIndex:-1,
                        hasMore:true
                    })
                    that.getMyWorks(true);
                }else{
                    console.log("success："+JSON.stringify(res.data))
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                console.log("fail："+JSON.stringify(res));
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    getMyWorks(isAdd){
        let that = this;
        if (!that.data.hasMore) return;
        wx.showLoading({
            title: '更新数据中...',
            mask: true
        })
        let pageI = ++that.data.pageIndex;
        this.setData({
            pageIndex: pageI
        });
        wx.request({
            url: app.globalData.serverAddress.getMyWorks,
            data: {
                pageSize: that.data.pageSize,
                pageIndex: pageI,
                currentUserInfoId: that.data.userInfoId,
                fileType: that.data.position == 1 ? 0 : 1 
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log(res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000){
                    console.log(res.data.BodyContent);
                    let list = res.data.BodyContent.List;
                    let count = res.data.BodyContent.TotalCount;
                    let flag = true;
                    let imgs = [];
                    let videos = [];
                    if(isAdd){
                        flag = that.data.currentTotal < count;
                        that.setData({
                            imgArr: [],
                            videoArr: [],
                        });
                        list.forEach(function (item) {
                            if (item.FileType == 0) {
                                imgs.push(item);
                            } else {
                                videos.push(item);
                            }
                        });
                    }else{
                        flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        imgs = that.data.imgArr;
                        videos = that.data.videoArr;
                        list.forEach(function (item) {
                            if (item.FileType == 0) {
                                imgs.push(item);
                            } else {
                                videos.push(item);
                            }
                        });
                        imgs.forEach(function(item , index){
                            if (item.IsCover == 1){
                                imgCoverIndex = index;
                            }
                        });
                        videos.forEach(function (item, index) {
                            if (item.IsCover == 1) {
                                videoCoverIndex = index;
                            }
                        });
                    }
                    that.setData({
                        imgArr: imgs,
                        videoArr: videos,
                        currentTotal: count,
                        hasMore:flag
                    })
                } else if (res.statusCode == 200 && res.data.CodeStatus == 40005){
                    that.setData({
                        hasMore:false
                    });
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
                Toast(res.data.Message);
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    uploadSyncFile(path) {
        let promis = new Promise(function (resolve, reject) {
            uploadFile({
                filePath: path,
                dir: 'xianjian_wx_image',
                success: function (res) {
                    resolve(res);
                },
                fail: function (res) {
                    reject(res);
                }
            });
        });
        return promis;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let obj = JSON.parse(options.parmas);
        this.setData({
            flag: obj.falg,
            userInfoId: obj.userInfoId
        });
        this.getMyWorks(false);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        this.getMyWorks(false);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})